using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using CE.User;
using CE.Mail;
using CE.Global;

public partial class User_EditProfile : MySessionBasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] != null && Session[CE.Global.General.UserTypeId] != null)
        {
            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) !=
                Convert.ToInt32(CE.Global.CEUserType.Customer) && Convert.ToInt32(Session[CE.Global.General.UserTypeId]) !=
                Convert.ToInt32(CE.Global.CEUserType.Provider))
            {
                Response.Redirect("~/car-insurance/login.aspx");
            }
        }
        else
        {
            Response.Redirect("~/car-insurance/login.aspx");
        }

        if (Page.ClientScript.IsStartupScriptRegistered("addScriptCheckAll") == false)
        {
            Page.ClientScript.RegisterStartupScript(Type.GetType("System.String"), "addScriptCheckAll", "CheckAll()", true);
        }

        if (!Page.IsPostBack)
        {
            usrDOB.StartYear = CE.Global.General.GetUTCDateTime().Year - 75;
            usrDOB.EndYear = CE.Global.General.GetUTCDateTime().Year - 18;

            DataTable dtCarYearDriveSg = General.GetComboItem("CarYearDriveSg", "[YearDriveSgId]", true);
            ddlYearDriveSg.DataSource = dtCarYearDriveSg;
            ddlYearDriveSg.DataTextField = dtCarYearDriveSg.Columns[0].ColumnName.ToString();
            ddlYearDriveSg.DataValueField = dtCarYearDriveSg.Columns[1].ColumnName.ToString();
            ddlYearDriveSg.DataBind();
            ddlYearDriveSg.Items.Insert(0, new ListItem("Select", "-1"));

            ddlYearDriveSg.Attributes.Add("onblur", "ShowValidationEffect('" + ddlYearDriveSg.ClientID + "','" + rfvYearDriveSg.ClientID + "');");

            ddlIDType.ClientValidationScript = "CheckIdTypePrefix();";
            txtIdNumber.ClientValidationScript = "CheckIdTypePrefix();";

            txtFirstName.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtFirstName.ClientID + "','" + rfvFirstName.ClientID + "','" + revFirstName.ClientID + "');");
            txtSurName.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtSurName.ClientID + "','" + rfvSurName.ClientID + "','" + revSurname.ClientID +"');");
            
            //txtHomePhoneNo.Attributes.Add("onblur", "ShowValidationEffectNoRequire('" + txtHomePhoneNo.ClientID + "','" + csvHomePhoneNo.ClientID + "');");
            //txtOfficeNo.Attributes.Add("onblur", "ShowValidationEffectNoRequire('" + txtOfficeNo.ClientID + "','" + csvOfficePhoneNo.ClientID + "');");
            ShowUserDetails();
        }
        LogUserViewedHistory();
        Page.Form.DefaultButton = btnSubmit.UniqueID;
    }

    private void LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        _userviewdb.LogViewedHistory("USR", Request, "User edit profile.");
    }

    protected void CheckIdTypePrefixValid(object sender, ServerValidateEventArgs args)
    {
        string strIdType = ddlIDType.GetIDType();
        string strIdPrefix = txtIdNumber.GetIdPrefix();
        bool bResult = true;

        if (strIdType == "-1" || strIdPrefix == "-1")
        {
            bResult = false;
        }

        if (strIdType == "SPR" || strIdType == "PR")
        {
            if (strIdPrefix != "S" && strIdPrefix != "T")
            {
                bResult = false;
            }
            else
            {
                bResult = true;
            }
        }
        else
        {
            if (strIdPrefix != "G" && strIdPrefix != "F")
            {
                bResult = false;
            }
            else
            {
                bResult = true;
            }
        }

        if (bResult == false)
        {

        }
        else
        {

        }

        args.IsValid = bResult;
    }

    //protected void CheckSalGenderValid(object sender, ServerValidateEventArgs args)
    //{
    //    string _sal = ddlSalutation.GetSalutation();
    //    string _gender = ddlGender.GetGender();
    //    if (_gender == "M")
    //    {
    //        if (_sal == "Ms" || _sal == "Miss" || _sal == "Mdm")
    //        {
    //            args.IsValid = false;
    //        }
    //    }
    //    else if (_gender == "F")
    //    {
    //        if (_sal == "Mr" || _sal == "Mrs")
    //        {
    //            args.IsValid = false;
    //        }
    //    }
    //    else
    //    {
    //        args.IsValid = true;
    //    }
    //}

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        //Salutation
        //ddlSalutation.ChangeValidationEffectServerSide(strValidationGroup);
        if (rfvFirstName.Enabled && rfvFirstName.ValidationGroup == strValidationGroup)
        {
            rfvFirstName.Validate();
            if (rfvFirstName.IsValid == false)
            {
                txtFirstName.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtFirstName.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtFirstName.ControlStyle.CssClass = "";
        }
        if (revFirstName.Enabled && revFirstName.ValidationGroup == strValidationGroup)
        {
            if (rfvFirstName.IsValid)
            {
                revFirstName.Validate();
                if (revFirstName.IsValid == false)
                {
                    txtFirstName.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtFirstName.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtFirstName.ControlStyle.CssClass = "";
        }

        //Surname
        if (rfvSurName.Enabled && rfvSurName.ValidationGroup == strValidationGroup)
        {
            rfvSurName.Validate();
            if (rfvSurName.IsValid == false)
            {
                txtSurName.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtSurName.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtSurName.ControlStyle.CssClass = "";
        }

        if (revSurname.Enabled && revFirstName.ValidationGroup == strValidationGroup)
        {
            if (rfvSurName.IsValid)
            {
                revSurname.Validate();
                if (revSurname.IsValid == false)
                {
                    txtSurName.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtSurName.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtSurName.ControlStyle.CssClass = "";
        }

        //Date of birth
        usrDOB.ChangeValidationEffectServerSide(strValidationGroup);

        //Gender
        ddlGender.ChangeValidationEffectServerSide(strValidationGroup);

        //Salutation and Gender
        //if (csvSalGender.Enabled && csvSalGender.ValidationGroup == strValidationGroup)
        //{
        //    if (ddlSalutation.IsValidRequirement() && ddlGender.IsValidRequirement())
        //    {
        //        csvSalGender.Validate();
        //        if (csvSalGender.IsValid == false)
        //        {
        //            ddlGender.ChangeValidateEffect(true);
        //            ddlSalutation.ChangeValidateEffect(true);
        //        }
        //        else
        //        {
        //            ddlGender.ChangeValidateEffect(false);
        //            ddlSalutation.ChangeValidateEffect(false);
        //        }
        //    }
        //}
        //else
        //{
        //    ddlGender.ChangeValidateEffect(false);
        //    ddlSalutation.ChangeValidateEffect(false);
        //}

        //Nationality
        ddlNationality.ChangeValidationEffectServerSide(strValidationGroup);

        //Mobile Number
        txtMobileNo.ChangeValidationEffectServerSide(strValidationGroup);

        //Type Of Indentification
        ddlIDType.ChangeValidationEffectServerSide(strValidationGroup);
        //ID Number
        txtIdNumber.ChangeValidationEffectServerSide(strValidationGroup);

        //ID Prefix & ID Type
        if (csvIdTypePrefix.Enabled && csvIdTypePrefix.ValidationGroup == strValidationGroup)
        {
            if (ddlIDType.IsValidRequirement() && txtIdNumber.IsValidePrefixRequirement())
            {
                csvIdTypePrefix.Validate();
                if (csvIdTypePrefix.IsValid == false)
                {
                    ddlIDType.ChangeValidateEffect(true);
                    txtIdNumber.ChangeValidateEffectPrefix(true);
                    csvIdTypePrefix.ErrorMessage = "Identification type and NRIC/FIN number's prefix character are not matched.";
                }
                else
                {
                    ddlIDType.ChangeValidateEffect(false);
                    txtIdNumber.ChangeValidateEffectPrefix(false);
                }
            }
        }
        else
        {
            ddlIDType.ChangeValidateEffect(false);
            txtIdNumber.ChangeValidateEffectPrefix(false);
        }

        //Year of Driving In SG
        if (rfvYearDriveSg.Enabled && rfvYearDriveSg.ValidationGroup == strValidationGroup)
        {
            rfvYearDriveSg.Validate();
            if (rfvYearDriveSg.IsValid == false)
            {
                ddlYearDriveSg.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlYearDriveSg.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlYearDriveSg.ControlStyle.CssClass = "";
        }

        if (csvAgeAndYear.Enabled && csvAgeAndYear.ValidationGroup == strValidationGroup)
        {
            csvAgeAndYear.Validate();
            if (csvAgeAndYear.IsValid == false)
            {
                ddlYearDriveSg.ControlStyle.CssClass = "validationError";
                usrDOB.ChangeValidationEffect();
            }
            else
            {
                ddlYearDriveSg.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlYearDriveSg.ControlStyle.CssClass = "";
        }
    }

    protected void CheckAgeAndYear(object sender, ServerValidateEventArgs args)
    {
        bool _isValid = true;
        DateTime _dtDOB = usrDOB.GetDate();
        int _expYear = Convert.ToInt32(ddlYearDriveSg.Text);
        int _age = CE.Global.General.GetUTCDateTime().Year - _dtDOB.Year;

        int _possibleExpYear = _age - 18;

        if (_possibleExpYear < 0)
        {
            _isValid = false;
        }
        else if (_expYear > _possibleExpYear)
        {
            _isValid = false;
        }

        args.IsValid = _isValid;
    }

    private void ShowUserDetails()
    {
        CE.User.Profile _profile = new CE.User.Profile();
        CE.User.ProfileDB _profiledb = new ProfileDB();
        CE.User.Contact _contact = new Contact();
        CE.User.ContactDB _contactdb = new ContactDB();
        Int64 UserId = Convert.ToInt64(Session[General.UserId].ToString());
        _profile = _profiledb.GetProfile(UserId);
        if (_profile != null)
        {
            //ddlSalutation.Saluation = _profile.Salutation;
            txtFirstName.Text = _profile.FirstName;
            txtSurName.Text = _profile.SurName;
            //if (_profile.FirstName != string.Empty)
            //{
            //    txtFirstName.Text = _profile.FirstName;
            //}
            usrDOB.Day = _profile.DOB.Day;
            usrDOB.Month = _profile.DOB.Month;
            usrDOB.Year = _profile.DOB.Year;

            ddlGender.Gender = _profile.Gender.ToString();
            if (_profile.MaritalStatus != -1)
                ddlMaritalStatus.MaritalStatus = _profile.MaritalStatus.ToString();

            if (_profile.Occupation != -1)
                ddlOccupation.Occupation = _profile.Occupation.ToString();

            if (_profile.JobNature != string.Empty)
                ddlJobNature.JobNature = _profile.JobNature;

            if (_profile.IDType != string.Empty)
                ddlIDType.IdType = _profile.IDType;

            if (_profile.IDNo.Length == 9)
            {
                txtIdNumber.Prefix = _profile.IDNo[0].ToString();
                txtIdNumber.Postfix = _profile.IDNo[8].ToString();
                txtIdNumber.IDNumber = _profile.IDNo.Substring(1, 7);
            }

            ddlNationality.Nationality = _profile.Nationality;
            ddlYearDriveSg.Text = _profile.YearDriveSg.ToString();

            _contact = _contactdb.GetContact(UserId);
            if (_contact != null)
            {
                txtMobileNo.PhoneNo = _contact.Mobile;
                txtHomePhoneNo.PhoneNo = _contact.HomePhone;
                txtOfficeNo.PhoneNo = _contact.OfficePhone;
            }

            if (Session[CE.Global.General.UserProfileAndContactComplete].ToString() == "1")
            {
                usrDOB.IsEnabled = false;
                ddlGender.IsEnabled = false;
            }
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {

        ChangeValidationEffectServerSide("profile");
        if (Page.IsValid)
        {
            txtFirstName.Text = CE.Global.General.ClearScriptTag(txtFirstName.Text);
            txtSurName.Text = CE.Global.General.ClearScriptTag(txtSurName.Text);
            //txtFirstName.Text = CE.Global.General.ClearScriptTag(txtFirstName.Text);
            Int64 _userId = Convert.ToInt64(Session[General.UserId].ToString());
            Profile _userprofile = null;
            ProfileDB _userprofiledb = new ProfileDB();
            Contact _contact = null;
            ContactDB _contactdb = new ContactDB();

            if (_userId > 0)
            {
                _userprofile = _userprofiledb.GetProfile(_userId);
                if (_userprofile == null)
                {
                    _userprofile = new Profile();
                }

                //_userprofile.Salutation = ddlSalutation.GetSalutation();
                _userprofile.FirstName = Server.HtmlEncode(txtFirstName.Text.ToUpper());
                _userprofile.SurName = Server.HtmlEncode(txtSurName.Text.ToUpper());
                _userprofile.DOB = usrDOB.GetDate();
                _userprofile.Gender = Convert.ToChar(ddlGender.GetGender());

                _userprofile.MaritalStatus = Convert.ToInt32(ddlMaritalStatus.GetMaritalStatus());
                _userprofile.JobNature = ddlJobNature.GetJobNature();
                _userprofile.Occupation = Convert.ToInt32(ddlOccupation.GetOccupation());

                _userprofile.IDType = ddlIDType.GetIDType();
                _userprofile.IDNo = txtIdNumber.GetIdNumber();

                _userprofile.Nationality = ddlNationality.GetNationality();
                _userprofile.YearDriveSg = Convert.ToInt16(ddlYearDriveSg.Text);

                _userprofile.RefCEUserId = _userId;
                _userprofile.Status = "Complete";
                
                Int64 _profileresult = _userprofiledb.Insert(_userprofile);

                _contact = _contactdb.GetContact(_userId);
                if (_contact == null)
                {
                    _contact = new Contact();
                }

                _contact.Mobile = Server.HtmlEncode(txtMobileNo.GetPhoneNo());
                _contact.HomePhone = txtHomePhoneNo.GetPhoneNo();
                _contact.OfficePhone = txtOfficeNo.GetPhoneNo();
                _contact.Status = true;
                _contact.RefCEUserId = _userId;
                Int64 _contactresult = _contactdb.Insert(_contact);

                if (_profileresult > 0 && _contactresult > 0)
                {
                    if (txtFirstName.Text != string.Empty)
                        Session[General.UserName] = txtSurName.Text.ToUpper() + " " + txtFirstName.Text.ToUpper();
                    else
                        Session[General.UserName] = txtSurName.Text.ToUpper();

                    Session[General.UserPhoneNo] = txtMobileNo.GetPhoneNo();
                    if (_userprofile.YearDriveSg > 0)
                    {
                        Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                    }

                    string _urlPath = "~/";
                    try
                    {
                        if (Page.Request.Params["redir"] != null)
                        {
                            string _tempUrlPath = GetRedirectUrl(Page.Request.Params["redir"].ToString());
                            string testUrl = Server.MapPath(_tempUrlPath);
                            _urlPath = Server.UrlDecode(_tempUrlPath);
                        }
                    }
                    catch (Exception Ex)
                    {
                        Ex = null;
                        _urlPath = "~/";
                    }
                    finally
                    {
                        Response.Redirect(_urlPath);
                    }
                }
            }
        }
    }

    private string GetRedirectUrl(string strPathId)
    {
        string retValue = "";
        //HF Require Loan
        if (strPathId == "201")
        {
            retValue = "~/home_refinancing/required_loan.aspx";
        }
        else if (strPathId == "201")
        {
            retValue = "~/home_refinancing/applicants_details.aspx";
        }
        else if (strPathId == "301")
        {
            retValue = "~/credit_cards/credit_card.aspx";
        }
        else if (strPathId == "302")
        {
            retValue = "~/credit_cards/applicants_details.aspx";
        }
        else if (strPathId == "401")
        {
            retValue = "~/personal_loan/personal_loan.aspx";
        }
        else if (strPathId == "402")
        {
            retValue = "~/personal_loan/applicants_details.aspx";
        }
        else if (strPathId == "501")
        {
            retValue = "~/personal-accident/";
        }
        else if (strPathId == "502")
        {
            retValue = "~/personal-accident/paproposalform.aspx";
        }
        else if (strPathId == "601")
        {
            retValue = "~/travel-insurance/";
        }
        else if (strPathId == "601")
        {
            retValue = "~/travel-insurance/applicants_details.aspx";
        }
        else
        {
            retValue = "~/";
        }

        return retValue;
    }
}
